/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.garagesale.user.web.action;

import com.garagesale.data.DBAccess;
import com.garagesale.data.ShoppingCart;
import com.garagesale.data.User;
import com.garagesale.user.web.form.UserForm;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author christophe
 */
public class SaveUserAction extends org.apache.struts.action.Action {
    
    /* forward name="success" path="" */
    private static final String SUCCESS = "success";
    
    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {


        UserForm userForm = (UserForm)form;
        User user = userForm.toUser();
        int userID;

        // TODO: Check to see if the current user is in the session

        if (null == userForm.getUserID() || userForm.getUserID() == 0)
        {
            // this user needs to be created
            user.setUserRole("user");
            userID = DBAccess.getInstance().create(user);

            // now create a cart for this user

            Date today = new Date();
            ShoppingCart cart = new ShoppingCart(
                        user,
                        request.getSession().getId(),
                        today,
                        today,
                        null);
            DBAccess.getInstance().create(cart);

        }
        else
        {
            // get the current user's role

            User sessionUser = (User)request.getSession().getAttribute("user");
            // get the session user's role and apply it to what's getting updated
            user.setUserRole(sessionUser.getUserRole());

            DBAccess.getInstance().update(user);
            userID = userForm.getUserID();
        }

        // make sure that the most up-to-date user is in the session

        User retrievedUser = DBAccess.getInstance().retrieveByID(User.class, userID);

        request.getSession().setAttribute("user", retrievedUser);

        return new ActionForward("/user/viewUser.do?userID=" + userID + "&created=true", true);
    }
}
